<?php

namespace App\Http\Controllers\Bend;


use App\Http\Controllers\Controller;
use App\Logics\UserLogic;
use App\Logics\ArtHtml\AdminForm;
use App\Logics\ArtHtml\AdminList;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Cookie;


class BaseController extends Controller
{
    protected $model;
    protected $error;
    protected $controller;

    // 页面
    protected $adminList;
    protected $adminForm;

    // 保存用户信息
    //    因为用户信息，可能会多次获取，所以保存下来直接返回
    protected static $userInfo;

    // 初始化
    public function initialize()
    {
        $user = $this->myUser();
        $opt  = $this->optLogic();
        // 权限判断 通过控制器来判断
        $controller = $opt->getData('controller', 'home', 'trim');
        $action     = $opt->getData('action', 'home', 'trim');

        $this->myUid      = $user['id'] ?? 0;
        $this->myUser     = $user;
        $this->controller = $controller;

        $opt->setField('myUid', $this->myUid);
        $opt->assign('is_encode', true);
        $opt->assign('myUser', $user);
        $opt->assign('controller', $controller);
        $opt->assign('back_site_name', 'hi艺库教育B端管理系统');
        $opt->assign('action', $action);
        $opt->assign('encodeConfig', $this->encodeConfig());
        $opt->assign('init_url', Url('/bend/'.$controller.'/lists'));
        $opt->assign('formUrl', url('/bend/'.$controller.'/on-'.($action == 'add' ? 'add' : 'edit')));


        // 所有的人都可以操作的控制器：测试，登录，
        if(!in_array($controller, ['account', 'test', 'search', 'deal',])){
            // TODO 必须登录
            if(empty($user)){
                if($this->request->ajax()){
                    $opt->throwIf(true, '请登录后在操作！');
                } else{
                    $this->jumpLogin();
                }
            }

            $opt->throwIf(empty($user['is_auth']), '你没有认证！');
            $opt->throwIf($user['verify'] != 1, '你的用户认证未通过！');

            // 设置目录
            //$this->menus();
        }
    }

    // 验证用户密码
    public function checkPassword()
    {
        if(empty($this->myUser)){
            return $this->error('登录已经过期，请先登录在操作！');
        }

        $logic = new UserLogic();
        $res   = $logic->checkPassword($this->myUser['id']);
        if($res === false){
            return $this->error($logic->getError());
        }

        return $this->success();
    }

    #######################################################################################################
    ## 页面
    // 添加
    public function add()
    {
        //$info = $this->info();
        // $this->controller.'.form'
        $form = $this->formTable();

        return $this->dispaly('form_pop', ['formHtml' => $form]);
    }

    // 修改
    public function edit()
    {
        //$info = $this->info();
        $form = $this->formTable();

        return $this->dispaly('form_pop', ['formHtml' => $form]);
    }

    // 列表（如果是树状的时候，可以重写该方法就好，页面不用处理）
    public function lists()
    {
        // 操作
        $option = $this->optLogic();
        $logic  = $this->checkLogic($this->model);
        $is_pop = $option->getData('is_pop', null, 'intval');
        if($logic === false){
            return $this->error($logic->getError());
        }

        // 执行
        //$result = $logic->onCount();
        $option->setField('is_count', 1);
        $this->listSearch();
        $this->listTopButton();
        $this->assign('request', $this->optLogic()->getData());
        $this->assign('fields', $this->listFields());

        // 获取列表
        $result = $logic->onLists();
        if($result === false){
            return $this->error($logic->getError());
        }
        // 列表展示
        $result['tr'] = $this->listTable($result['list']);

        //var_dump($result['pages']);
        if($is_pop){
            return $this->dispaly('lists_pop', $result);
        }else{
            return $this->dispaly('lists', $result);
        }
    }

    #######################################################################################################
    ## html
    protected function formTable() { return ''; }

    // 列表搜索
    protected function listSearch()
    {
        $request = $this->optLogic()->getData();
        $form    = $this->adminList();
        $keyword = $form->formInput('keyword', $request['keyword'] ?? '', '关键字');
        $search  = ['keyword' => $keyword,];  // keyword
        $this->assign('search', $search);

        $searchHide = ['channel'];
        $this->assign('searchHide', []);
    }

    // 列表顶部按钮
    protected function listTopButton()
    {
        $addUrl     = Url('/innerend/course-sign/add');
        $top_button = '<a href="javascript:;" onclick="onEdit(\''.$addUrl.'\')" class="btn btn-success radius">添加课程签到</a> ';
        //$this->assign('top_button', $top_button);

        $this->assign('top_button', '');
    }

    // 列表字段
    protected function listFields()
    {
        // 'role' => '角色',
        return ['id' => '编号', 'operate' => ['操作', 250],];
    }

    // 列表数据展示
    protected function listTable($lists)
    {
        // 整理
        $trList = [];
        if(empty($lists)){
            return $trList;
        }

        // 整合
        return [];
    }

    // 列表页面
    protected function adminList()
    {
        if(empty($this->adminList)){
            $controller      = $this->optLogic()->getData('controller', 'home', 'trim');
            $this->adminList = new AdminList('bend', $controller);
        }

        return $this->adminList;
    }

    // 表单页面
    protected function adminForm()
    {
        if(empty($this->adminForm)){
            $controller      = $this->optLogic()->getData('controller', 'home', 'trim');
            $this->adminForm = new AdminForm('bend', $controller);
        }

        return $this->adminForm;
    }
    ###############################################################################################
    ## 数据操作
    ###############################################################################################
    // 查询统计
    public function onCount()
    {
        $logic = $this->checkLogic($this->model);
        if($logic === false){
            return $this->error($logic->getError());
        }

        $result = $logic->onCount();
        if($result === false){
            return $this->error($logic->getError());
        }

        return $this->success($result);
    }

    // 返回列表数据
    public function onLists()
    {
        $logic = $this->checkLogic($this->model);
        if($logic === false){
            return $this->error($logic->getError());
        }

        $lists = $logic->onLists();
        if($lists === false){
            return $this->error($logic->getError());
        }

        $trList = $this->listTable($lists);
        $result = ['tr' => $trList, 'list' => $lists];

        return $this->success($result);
    }

    // 删除
    public function onDelete()
    {
        $logic = $this->checkLogic($this->model);
        if($logic === false){
            return $this->error($logic->getError());
        }

        $result = $logic->onDelete($this->myUid);
        if($result === false){
            return $this->error($logic->getError());
        }

        return $this->success();
    }

    // 批量删除
    public function batchDelete()
    {
        $logic = $this->checkLogic($this->model);
        if($logic === false){
            return $this->error($logic->getError());
        }

        $result = $logic->batchDelete($this->myUid);
        if($result === false){
            return $this->error($logic->getError());
        }

        return $this->success();
    }

    // 软删除
    public function onSoft()
    {
        $logic = $this->checkLogic($this->model);
        if($logic === false){
            return $this->error($logic->getError());
        }

        $result = $logic->onSoft($this->myUid);
        if($result === false){
            return $this->error($logic->getError());
        }

        return $this->success();
    }

    // 启用禁用
    public function onStatus()
    {
        $logic = $this->checkLogic($this->model);
        if($logic === false){
            return $this->error($logic->getError());
        }

        $result = $logic->onStatus();
        if($result === false){
            return $this->error($logic->getError());
        }

        return $this->success([], '更新成功！');
    }

    // TODO 详情：修改的时候要使用的
    public function onShow()
    {
        $logic = $this->checkLogic($this->model);
        if($logic === false){
            return $this->error($logic->getError());
        }

        $info = $logic->onShow($this->myUid);
        if($info === false){
            return $this->error($logic->getError());
        }

        return $info;
    }

    // 修改
    public function onEdit()
    {
        $logic = $this->checkLogic($this->model);
        if($logic === false){
            return $this->error($logic->getError());
        }

        $result = $logic->onEdit($this->myUid);
        if($result === false){
            return $this->error($logic->getError());
        }

        return $this->success();
    }

    // 添加
    public function onAdd()
    {
        $logic = $this->checkLogic($this->model);
        if($logic === false){
            return $this->error($logic->getError());
        }

        $result = $logic->onAdd($this->myUid);
        if($result === false){
            return $this->error($logic->getError());
        }

        return $this->success();
    }

    #######################################################################################################
    // 修改的详情
    protected function info()
    {
        return [];
    }

    // 判断操作模型是否存在
    protected function checkLogic($logic = '')
    {
        $this->optLogic()->throwIf(empty($logic), '请指定操作！！');
        // 模型 与 查询
        $logic = 'App\Logics\\'.ucwords($logic).'Logic';
        if(!class_exists($logic)){
            $request = request();
            $real_ip = $request->getClientIp();
            $test_ip = env('TEST_IP');
            $this->optLogic()->throwIf(true, $logic.'操作不存在！！');

            //$this->throwIf($real_ip == $test_ip, '模型不存在！！');

            return false;
        }

        return new $logic;
    }

    // 获取用户以及权限
    protected function myUser()
    {
        $user = $this->optLogic()->request()->session()->get('organ_user');
        if(empty($user)){
            $user = Cookie::get('organ_user');
            if(empty($user)){
                return [];
            }

            $user = json_decode($user, true);
        }
        if(empty($user)){
            return [];
        }

        $logic = new UserLogic();
        $info  = $logic->info($user['id']);
        $info  = is_object($info) ? $info->toArray() : $info;
        if(empty($info)){
            //$this->jumpLogin('登录过期，请重新登录！！');
            return [];
        }
        if($info['status'] != 1){
            // TODO 如果用户被禁用，应该清空 cookie 不然会一直进入循环请求
            //$this->jumpLogin('用户被禁用！！');
            return [];
        }
        // 组合
        $info['uid'] = $info['id'];

        $this->optLogic()->setUser($info);

        return $info;
    }

    // 获取加密配置
    protected function encodeConfig()
    {
        $conf = Config::get('encrypt');

        // 长度
        $conf['iv_len']  = 16;
        $conf['key_len'] = 24;
        $conf['key']     = substr($conf['key'], 0, 24);
        $conf['iv']      = substr($conf['iv'], 0, 16);

        // 暂时不要加密
        //$conf = [];

        return $conf;
    }

    // 展示转跳登录
    protected function jumpLogin($msg = '请重新登录在操作！')
    {
        // 删除cookie后需要重新定向
        //$cookie = Cookie::forget('organ_user');
        //$url    = htmlUrl('bend/account/login');
        $url = Url('bend/account/login');

        die($this->jumpTo($url, $msg));
        //return Redirect::secure($url)->withCookie($cookie);
    }

    // 转跳页面
    protected function jumpTo($url, $message = '')
    {
        return $this->dispaly('jump', ['url' => $url, 'message' => $message,]);
    }

    // 加载模板输出
    protected function dispaly($template, $vars = [])
    {
        return $this->optLogic()->dispaly('bend.'.$template, $vars, false);
    }

    protected function assign($name, $value = '')
    {
        return $this->optLogic()->assign($name, $value);
    }

    // 已经传递的数据
    protected function getAssign($name, $value = '')
    {
        return $this->optLogic()->getAssign($name, $value);
    }
}


